<?php
require_once 'helpers.php';

use Pecee\SimpleRouter\SimpleRouter;
use GeoIp2\Database\Reader;
use GeoIp2\Exception\AddressNotFoundException;
use MaxMind\Db\Reader\InvalidDatabaseException;

SimpleRouter::get('/', function () {
    return 'Hello world';
});

SimpleRouter::get('/ip/simple', function () {
    $ip = '';
    $k_arr = ['REMOTE_ADDR', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'];
    foreach ($k_arr as $k) {
        if (isset($_SERVER[$k]) && !empty($_SERVER[$k])) {
            $ip = $_SERVER[$k];
            break;
        }
    }
    return $ip;
});

SimpleRouter::get('/ip/proxy', function () {
    $ips = [];
    $k_arr = ['REMOTE_ADDR', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'];
    foreach ($k_arr as $k) {
        if (isset($_SERVER[$k]) && !empty($_SERVER[$k])) {
            $ips[] = $_SERVER[$k];
            break;
        }
    }
    return response()->json($ips, JSON_UNESCAPED_UNICODE);
});

SimpleRouter::get('/ip', function () {
    $reader = new Reader('../data/GeoLite2-City.mmdb');
    $ip = input()->get('q', $defaultValue = null);
    if (is_null($ip)) {
        $k_arr = ['REMOTE_ADDR', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'];
        foreach ($k_arr as $k) {
            if (isset($_SERVER[$k]) && !empty($_SERVER[$k])) {
                $ip = $_SERVER[$k];
                break;
            }
        }
    }
    try {
        $record = $reader->city($ip);
    } catch (AddressNotFoundException $e) {
        return $e->getMessage();
    } catch (InvalidDatabaseException $e) {
        return response($e);
    }
    return response()->json($record, JSON_UNESCAPED_UNICODE);
});